//
//  AVAsset+Extension.swift
//  TA
//
//  Created by M on 2019/12/11.
//  Copyright © 2019 m. All rights reserved.
//

import UIKit
import AVFoundation

extension AVAsset {
    
    static var TemporaryFolderPath: String? {
        let cachesPath: AnyObject = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] as AnyObject
        let folderPath = cachesPath.appending("/AVAssetTemporaryExportPath")
        var isDir: ObjCBool = false
        let existed = FileManager.default.fileExists(atPath: folderPath, isDirectory: &isDir)
        if !isDir.boolValue && !existed {
            do {
                try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
            } catch {
                debugPrint(error.localizedDescription)
                return nil
            }
        }
        return folderPath
    }
    
    /**
    缓存视频
     
    path: 保存路径 - 可选 （如 nil，则生成新的路径）
     */
    public func export(withPath path: String?,
                       presetName: String = AVAssetExportPreset1280x720,
                       errorHandler: ((_ error: Error?) -> Swift.Void)?,
                       completion: @escaping (_ progress: Float, _ path: String?) -> Swift.Void) {
        
        if AVAssetExportSession.exportPresets(compatibleWith: self).contains(presetName) {
            guard let session = AVAssetExportSession(asset: self, presetName: presetName), let folderPath = AVAsset.TemporaryFolderPath else { return }
            let arc = "\(arc4random()%100000)\(Int(Date().timeIntervalSince1970))"
            let generatedPath = folderPath + "/" + arc
            let exportPath = path ?? generatedPath
            session.outputURL = URL(fileURLWithPath: exportPath)
            session.shouldOptimizeForNetworkUse = true
            
            MTTimer.default.scheduledTimer(withName: exprortTimerName, timeInterval: 0.1, queue: .global(), repeats: true) {
                completion(session.progress, nil)
            }
            
            let supportTypes = session.supportedFileTypes
            if supportTypes.contains(.mov) {
                session.outputFileType = .mov
            } else {
                session.outputFileType = supportTypes[0]
            }
            
            session.exportAsynchronously { [weak self] in
//         case unknown, waiting, exporting, completed, failed, cancelled
                switch session.status {
                case .completed:
                    if let weakself = self {
                        MTTimer.default.removeTimer(name: weakself.exprortTimerName)
                    }
                    completion(1, exportPath)
                    break
                    
                case .failed, .cancelled:
                    if let weakself = self {
                        MTTimer.default.removeTimer(name: weakself.exprortTimerName)
                    }
                    if let handler = errorHandler {
                        handler(session.error)
                    }
                    break
                    
                default:
                    if let handler = errorHandler {
                        handler(session.error)
                    }
                    break
                }
            }
        }
        
    }
    
    private var exprortTimerName: String {
        return "com.mitu.exportTimerName"
    }
    
}
